/*
 * @Author: yanjikun
 * @Date: 2021-06-21 14:54:10
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-05-31 11:40:40
 * @Description: file content
 */
import { RouteRecordRaw } from 'vue-router'
import { constantRouterComponents } from './constantRouterComponents'
import { Empty } from 'ant-design-vue'
import router, { routes } from '@/router/index'
import { isUrl } from '@/utils/is'
import { getUserRights } from '@/api/global'
import { MENU_TYPE } from '@/enums/constantEnums'
import { error } from '@/utils/log'
import { errorRoute, notFound } from './staticModules/error'
// import outsideLayout from './staticModules/outsideLayout'

/** 需要放在所有路由之后的路由 */
const endRoutes: RouteRecordRaw[] = [errorRoute, notFound]
export const listToRouter = (
  list: API.MenuResult,
  parentId: number | null = -1,
  pathPrefix: string = '',
): RouteRecordRaw[] => {
  return list
    .filter((item: API.IMenuItem) => item.parentId === parentId && item.type === MENU_TYPE.MENU)
    .sort((a, b) => a.sort - b.sort)
    .map((item): RouteRecordRaw => {
      const { url, id, name, icon, keepAlive, hidden } = item
      let path = ''
      if (isUrl(url)) {
        path = url
      } else {
        path = url.startsWith('/') ? url : `/${url}`
        path = path.startsWith(pathPrefix) ? path : `${pathPrefix}/${url}`
        path = [...new Set(path.split('/'))].join('/')
      }
      const component = constantRouterComponents[path] || Empty
      const children = listToRouter(list, id, path)
      return {
        path,
        name: path || '',
        component: component,
        children: children,
        redirect: children.length ? { name: children[0].name } : undefined,
        meta: {
          title: name,
          icon: icon || '',
          keepAlive: keepAlive === 1,
          hidden: hidden === 1,
        },
      }
    })
}

export const generatorDynamicRouter = (): Promise<RouteRecordRaw[]> => {
  return new Promise((resolve, reject) => {
    getUserRights()
      .then((res) => {
        try {
          const routers = listToRouter(res, null, '')
          const layout = routes.find((item) => item.name === 'Layout')!
          layout.children = [...routers, ...endRoutes]
          // const removeRoute = router.addRoute(layout as RouteRecordRaw)
          // const filterRoutes = router
          //   .getRoutes()
          //   .filter(
          //     (item) =>
          //       (!item.children?.length || Object.is(item.meta?.hidden, true)) &&
          //       outsideLayout.every((n) => n.name !== item.name),
          //   )
          // /**清空所有路由 */
          // removeRoute()
          // layout.children = [...filterRoutes]
          // layout.redirect = filterRoutes[0]?.path ?? '404'
          layout.redirect = layout.children[0]?.path ?? '404'
          router.addRoute(layout)
          resolve(routers)
        } catch (err) {
          error(err as string)
          reject()
        }
      })
      .catch(() => {
        reject()
      })
  })
}
